var express = require('express');
var router = express.Router();
let { users_Model } = require('../mongoose/index')
const jwt = require('jsonwebtoken')


//注册接口 
router.post('/register', async (req, res) => {
  let body = req.body;
  let obj = await users_Model.findOne({ phone: body['phone'] })
  obj ? res.send({ code: 500, msg: `账号已存在` }) :
    (users_Model.create(body), res.send({ code: 201, msg: `注册成功` }))
})

//登录接口
router.post('/login', async (req, res) => {
  let body = req.body;
  let obj = await users_Model.findOne({ phone: body['phone'] });
  if (obj) {
    let token = 'Bearer ' + jwt.sign({ phone: body['phone'] }, 'lichune', { expiresIn: '1h' });
    res.send({ code: 201, msg: `登录成功`, token }) //登录成功
  } else {
    let token = 'Bearer ' + jwt.sign({ phone: body['phone'] }, 'lichune', { expiresIn: '1h' })
    await users_Model.create(body)
    res.send({ code: 201, msg: `注册成功`, token })
  }
})

//发送验证码
//引入阿里云短信服务模块
const SMSClient = require('@alicloud/sms-sdk');
//产生6位随机数(用来生成短信验证码的
function getCode() {
  let str = ""
  for (let i = 0; i < 6; i++) {
    str += parseInt(Math.random() * 10)
  }
  return str;
}
//发送验证码
router.get('/sendCode/:phone', (req, res) => {
  let phone = req.params.phone;  //获取用户手机号
  let smsClient = new SMSClient({
    accessKeyId: "LTAI5tLTTETkpLm9cdnoYHZH",
    secretAccessKey: "loYjHy65zm11WcBjyIgVVGEEQWKy2n"
  })
  let keyCode = getCode()  //获取验证码
  smsClient.sendSMS({
    PhoneNumbers: phone,
    SignName: "智慧在线教育平台",
    TemplateCode: "SMS_460730179", //模版CODE前面提到要准备的
    TemplateParam: `{"code":'${keyCode}'}`
  }).then(result => {
    console.log('请求成功');
    let { Code } = result;
    if (Code == 'OK') return res.json({ code: 0, msg: 'success', sms: keyCode })
  }).catch(err => {
    console.log('请求失败');
    res.json({
      code: 1,
      msg: 'fail: ' + err.data.Message
    })
  })

})





module.exports = router;
